<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24" v-if="!tenantid">
            <a-form-item :label="$t('门店')">
              <a-select v-model="queryParam.tenantId">
                <a-select-option v-for="(item, i) in shops" :key="i" :value="item.value"
                  >{{ item.title }}<span v-if="item.value != ''">（{{ item.value }}）</span></a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="6" :md="8" :sm="24">
            <a-form-item :label="$t('年份')">
              <a-date-picker
                :allowClear="false"
                mode="year"
                format="YYYY"
                valueFormat="YYYY"
                :open="isopen"
                @openChange="openChange"
                @panelChange="panelChange"
                :placeholder="$t('请选择')"
                v-model="queryParam.year"
                style="width: 100%"
              ></a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :xl="10" :lg="12" :md="12" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{ $t('查询') }}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{
                $t('重置')
              }}</a-button>
            </span>
          </a-col>
          <template v-if="toggleSearchStatus"></template>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- table区域-begin -->
    <a-row style="margin-top: 20px">
      <a-col :span="12">
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          class="j-table-force-nowrap"
          :scroll="{ x: true }"
          :columns="columns"
          :dataSource="dataSources"
          :pagination="false"
          :loading="loading"
          :customRow="customRow"
        >
          <template slot="htmlSlot" slot-scope="text">
            <div v-html="text"></div>
          </template>
          <template slot="imgSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无图片') }}</span>
            <img
              v-else
              :src="getImgView(text)"
              height="25px"
              alt
              style="max-width: 80px; font-size: 12px; font-style: italic"
            />
          </template>
          <template slot="fileSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px; font-style: italic">{{ $t('无文件') }}</span>
            <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">{{
              $t('下载')
            }}</a-button>
          </template>
        </a-table>
      </a-col>
      <a-col :span="12">
        <div class="down-charts" id="myChart5"></div>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
import Vue from 'vue'
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
let myChart5

export default {
  name: 'MonthlySalesSummary',
  mixins: [JeecgListMixin],
  components: {},
  data() {
    return {
      moment,
      description: '月销售汇总页面',
      // 表头
      columns: [
        {
          title: this.$t('月份'),
          align: 'center',
          dataIndex: 'date',
        },
        {
          title: this.$t('c_数量'),
          align: 'center',
          dataIndex: 'amount',
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('c_金额'),
          align: 'center',
          dataIndex: 'price',
          customRender: (t, r) => {
            let arr = t.toString().split('.')
            if (arr.length > 1 && arr[1].length > 2) {
              return t.toFixed(2)
            }
            return t
          },
          customCell: (r, i) => {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
      ],
      queryParam: {
        year: moment().format('YYYY'),
        tenantId: '',
      },
      url: {
        list: '/report/goods/salesSummary/monthList',
      },
      shops: [],
      isCustom: true,
      tenantid: Vue.ls.get('TENANT_ID'),
      dataSources: [],
      isopen: false,
    }
  },
  created() {
    if (!this.tenantid) {
      initDictOptions('bis_shop,name,code').then((res) => {
        if (res.success) {
          this.shops = res.result
          this.shops.unshift({ value: '', title: this.$t('全部') })
        }
      })
    }
    this.initDictConfig()
  },
  watch: {
    dataSource(nlist) {
      this.test5(nlist)
      this.dataSources = nlist.slice()
      this.addSumRow(['date', 'amount', 'price'], this.dataSources)
    },
  },
  methods: {
    openChange(status) {
      if (status) {
        this.isopen = true
      } else {
        this.isopen = false
      }
    },
    panelChange(value) {
      this.queryParam.year = moment(value).format('YYYY')
      this.isopen = false
    },
    customRow(r, i) {
      return {
        style: {
          fontWeight: r.date == this.$t('合计') ? 700 : 400,
        },
      }
    },
    addSumRow(myArr, dataSource) {
      let that = this,
        total = {}
      myArr.forEach(function (tcn, ind) {
        if (ind == 0) {
          total[tcn] = that.$t('合计')
        } else {
          total[tcn] = 0
        }
      })
      for (let key in total) {
        dataSource.forEach(function (ds) {
          if (!isNaN(total[key])) {
            total[key] += Number(ds[key])
          }
        })
      }
      dataSource.push(total)
    },
    initDictConfig() {
      this.searchQuery()
      this.$nextTick(() => {
        myChart5 = this.$echarts.init(document.getElementById('myChart5'), 'light')
        myChart5.showLoading({
          text: 'loading',
          color: '#000',
          maskColor: 'rgba(255, 255, 255, 0.8)',
        })
      })
    },
    searchReset() {
      this.queryParam = {
        year: moment().format('YYYY'),
        tenantId: '',
      }
      this.searchQuery()
    },
    test5(list) {
      let that = this
      myChart5 = this.$echarts.init(document.getElementById('myChart5'), 'light')
      // 经营总收入
      myChart5.hideLoading()
      let legendData = [],
        text = '',
        series = [],
        yAxis,
        minArr = []
      myChart5.clear()
      text = this.$t('销售汇总')
      legendData = [this.$t('c_数量'), this.$t('c_金额')]
      minArr.push(that.min3(list, 'amount'))
      minArr.push(that.min3(list, 'price'))
      yAxis = {
        type: 'value',
        min: that.min3(minArr),
      }
      series = [
        {
          name: this.$t('c_数量'),
          type: 'line',
          symbol: 'circle',
          symbolSize: 1,
          data: that.dataBarOrLineAxios(list, 'amount'),
          /* itemStyle: {
            normal: {
              color: '#F5A518',
            },
          }, */
        },
        {
          name: this.$t('c_金额'),
          type: 'line',
          symbol: 'circle', // 折线点设置为实心点
          symbolSize: 1, // 折线点的大小
          data: that.dataBarOrLineAxios(list, 'price'),
          /* itemStyle: {
            normal: {
              color: '#BF0FB0',
            },
          }, */
        },
      ]
      myChart5.setOption({
        title: {
          text: text,
          left: 'center',
          show: true,
        },
        tooltip: {
          trigger: 'axis',
          textStyle: {
            align: 'left',
          },
          formatter: function (params) {
            let str = params[0].name
            params.forEach((ps, ind) => {
              str +=
                '<br/>' +
                '<span style="display:inline-block;margin-right:6px;width:10px;height:10px;border-radius:10px;background-color:' +
                ps.color +
                ';"></span>' +
                ps.seriesName +
                ':' +
                ps.value
            })
            return str
          },
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999',
            },
          },
        },
        grid: {
          show: false,
          top: '60',
          bottom: '50',
          right: '60',
          left: '60',
        },
        legend: {
          show: true,
          data: legendData,
          bottom: 0,
          right: 'center',
          itemHeight: 6,
          itemWidth: 20,
          icon: 'roundRect',
          textStyle: {
            fontSize: 11,
          },
        },
        xAxis: {
          splitLine: { show: false },
          type: 'category',
          data: that.dayAxios(list),
          axisPointer: {
            type: 'shadow',
          },
          // 改变x轴颜色
          axisLine: {
            lineStyle: {
              width: 1, // 这里是为了突出显示加上的
            },
          },
          axisTick: {
            show: true,
            interval: 0,
          },
        },
        yAxis: yAxis,
        series: series,
      })
    },
    dayAxios(list, arg) {
      let dayAxios = []
      list.forEach((lt) => {
        if (arg) {
          let day = new Date(lt.date).getDay(),
            dayText = ''
          if (arg == 'week') {
            switch (day) {
              case 1:
                dayText = this.$t('周一')
                break
              case 2:
                dayText = this.$t('周二')
                break
              case 3:
                dayText = this.$t('周三')
                break
              case 4:
                dayText = this.$t('周四')
                break
              case 5:
                dayText = this.$t('周五')
                break
              case 6:
                dayText = this.$t('周六')
                break
              default:
                dayText = this.$t('周日')
                break
            }
            dayAxios.push(moment(new Date(lt.date)).format('MM-DD') + ' ' + dayText)
          }
          if (arg == 'month') {
            dayAxios.push(moment(new Date(lt.date)).format('yyyy-MM'))
          }
        } else {
          dayAxios.push(moment(new Date(lt.date)).format('MM-DD'))
        }
      })
      return dayAxios
    },
    dataBarOrLineAxios(list, arg) {
      let dataAxios = []
      list.forEach((lt) => {
        dataAxios.push(lt[arg])
      })
      return dataAxios
    },
    min3(list, arg, arg1) {
      let min = Math.min.apply(
        Math,
        list.map((item) => {
          let num = 0
          if (arg) {
            num = arg1 && arg1 == '1' ? Math.abs(item[arg]) : item[arg]
          } else {
            num = arg1 && arg1 == '1' ? Math.abs(item) : item
          }
          return num
        })
      )
      min = Math.floor(min)
      return Number(min)
    },
  },
}
</script>
<style scoped>
.down-charts {
  padding: 0;
  margin: 0;
  box-shadow: none;
  background: white;
  border-radius: 15px;
  height: 22vw;
}
</style>